package org.yuci.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.yuci.string.StringUtility;

public class IpAddrAnalyzer {

    /**
     * Extract the first valid IP address
     * 
     * Ref: http://stackoverflow.com/questions/15875013/extract-ip-addresses-from-strings-using-regex
     * 
     * @param ipString
     * @return
     */
    public static final String extractIpAddr(String ipString) {
        if (!StringUtility.hasContent(ipString)) {
            return null;
        }

        String IPADDRESS_PATTERN = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

        Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
        Matcher matcher = pattern.matcher(ipString);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return null;
        }
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        String ipAddr = extractIpAddr("fff::130.14.218:8690/AppPortal 130.14.21.1");
        System.out.println("ipAddr: " + ipAddr);
    }

}
